package mukirana;

import initialize.Console;

import java.awt.Toolkit;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.ResultSet;

import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;


import org.json.JSONArray;
import org.json.JSONObject;

import network.HttpURL;
 
public class Mukirana {

	Toolkit toolkit;
	HttpURL http;
	Connection connection;
	//Double lastlance=0.0;
	int qtdLances=0;
	//int lasttime=0;
	User user;
	//String usernamelastlance="";
	//Double usernamelastvalue=0.0;	
	List<Leilao> leilaoLogger = new ArrayList<Leilao>();
	boolean authentication=false;
	private Console windowInterface;
	
	public Mukirana( HttpURL http, Connection connection, User user, Console window ){
		
		this.http				=	http;
		this.connection			=	connection;
		this.user				=	user;
		this.toolkit			=	Toolkit.getDefaultToolkit();
		this.windowInterface	=	window;
		
		
		if( this.user.isAuthentic() ){
			
			String msgHello = "";
			
			this.authentication = authenticate( this.http, 
												user.getUsername(),
												user.getPassword() );
		
			if( !this.authentication ){
				msgHello	=	"falha na autenticacao.";
				
			}else{
				msgHello	=	"Logado com sucesso.\nusername:"+this.user.getUsername();
			}
			
			if( this.user.getCredit() <1 ){
				msgHello	=	msgHello+"\nSaldo insuficiente.\ncompre creditos.";				
				
			}else{
				msgHello	=	msgHello+"\nSeu saldo eh "+this.user.getCredit();
			}
			
			this.messageBox( msgHello, true );
		}
	}
	
	
	public boolean authenticate( HttpURL http, String username, String pwd ){

		boolean result=false;
		String tag="";
		
    	@SuppressWarnings("deprecation")
		String urlParameters = "user_session%5Busername%5D="
    							+URLEncoder.encode( username ).toString() +
    							"&user_session%5Bpassword%5D="
    							+URLEncoder.encode( pwd ).toString();
    	
		//fazendo o login
		//String sessao = executePost("http://www.mukirana.com/user_sessions", urlParameters);
		String targetURL	=	"http://www.mukirana.com/user_sessions";
		
		//autenticacao do usuario
		String html = http.post( targetURL, urlParameters );
		
		if( html.indexOf( "appear_fade(\"login_error\")" )>0){
			//falha ao autenticar
			tag = "update(\"login_error\"";
			
			if( html.indexOf( tag )>0 ){
				
				String login_error = html.substring( html.indexOf(tag)+tag.length()+3, html.length() );
				login_error = login_error.substring(0, login_error.indexOf("\")"));
				
				this.messageBox( login_error, true );
			}

			
		}else{
			
			if( html.indexOf( "closeEffect(\"signup\")" )>0 ){
				result=true;
				
				//System.out.println( html );
				
				String saldo = "";
				tag = "fixed_bids_count";//"<div id=\"fixed_bids_count\">";
				
				saldo = html.substring( html.indexOf(tag)+tag.length()+3, html.length() );
				saldo = saldo.substring(0, saldo.indexOf("</div>"));
				
				this.user.setCredit( Integer.parseInt( saldo ) );
			}
			
		}
		
		
		return result;
	}
	
	
	
	public void scannerAll() throws Exception{
		
		try{
        	
        	//final String json = "[{\"lb\":\"leojaera|fabiotadeu|caiolw|fabiotadeu|victorfialho23|fabiotadeu|tcbatista|silas86|drimdri|fabiotadeu|\",\"w\":0,\"st\":\"21 de Nov de 2011, 15:30\",\"x\":false,\"d\":20,\"p\":5.91,\"e\":false,\"id\":6042,\"sd\":1321894800,\"pc\":\"99.0\",\"s\":1321896649,\"bv\":0.01,\"t\":\"19\",\"u\":\"leojaera\"}, {\"st\":\"21 de Nov de 2011, 15:30\",\"x\":false,\"d\":15,\"p\":0.69,\"e\":false,\"id\":6043,\"sd\":1321898400,\"s\":1321896649,\"t\":\"15\",\"u\":\"peixotobh\"}, {\"st\":\"21 de Nov de 2011, 15:30\",\"x\":false,\"d\":20,\"p\":0.11,\"e\":false,\"id\":6046,\"sd\":1321900200,\"s\":1321896649,\"t\":\"20\",\"u\":\"carolinem\"}, {\"st\":\"21 de Nov de 2011, 15:30\",\"x\":false,\"d\":30,\"p\":0.19,\"e\":false,\"id\":6048,\"sd\":1321903800,\"s\":1321896649,\"t\":\"30\",\"u\":\"aposta57\"}]";	
        	
    		//final String json = "f1('[{\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":20,\"p\":18.86,\"e\":false,\"id\":6042,\"sd\":1321894800,\"s\":1321902329,\"t\":\"17\",\"u\":\"peixao\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":15,\"p\":11.73,\"e\":false,\"id\":6043,\"sd\":1321898400,\"s\":1321902329,\"t\":\"15\",\"u\":\"peixotobh\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":20,\"p\":5.18,\"e\":false,\"id\":6046,\"sd\":1321900200,\"s\":1321902329,\"t\":\"19\",\"u\":\"ha_muquirana\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":30,\"p\":0.22,\"e\":false,\"id\":6048,\"sd\":1321903800,\"s\":1321902329,\"t\":\"30\",\"u\":\"anderson1234\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":30,\"p\":0.31,\"e\":false,\"id\":6049,\"sd\":1321912800,\"s\":1321902329,\"t\":\"30\",\"u\":\"camilalapa\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":15,\"p\":1.36,\"e\":false,\"id\":6047,\"sd\":1321916400,\"s\":1321902329,\"t\":\"15\",\"u\":\"melissapinheiro\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":20,\"p\":0.16,\"e\":false,\"id\":6050,\"sd\":1321923600,\"s\":1321902329,\"t\":\"20\",\"u\":\"anderson1234\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":20,\"p\":0.31,\"e\":false,\"id\":6051,\"sd\":1321927200,\"s\":1321902329,\"t\":\"20\",\"u\":\"julinhoramos08\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":30,\"p\":0.15,\"e\":false,\"id\":6052,\"sd\":1321963200,\"s\":1321902329,\"t\":\"30\",\"u\":\"mariomrdesign\"}]');";
         	
    		Double microtime 	= 	(double) (System.currentTimeMillis() );      	
        	DecimalFormat df 	=	new DecimalFormat("##,###########");        	  
        	String currenttime	=	df.format(microtime);
        	int page			=	1;
        	        	
    		String url 			= 	"http://request1.mukirana.com/" +
    								"jsons/auctions_for_main_page_"
    								+page+"?_="+currenttime;//9.175279440106525";
    		
    		String json 		= 	this.http.get( url );
    		    		
    		//url para saber o que significa cada id de leilao
    		//http://request2.mukirana.com/jsons/load_auctions_for_show_6043?_=19.369437160053558    			
    			
        	String strClear = json.substring(4, json.length()-3);
         	JSONArray jObject = new JSONArray(strClear);

            for (int i = 0; i < jObject.length(); i++) {
            	
            	JSONObject noObject = jObject.getJSONObject(i);                 
                   
            	Leilao leilao 		=	new Leilao();            	
            	            	
               	leilao.setDateTimeLastLanceFormat( noObject.getString("st").toString() );//data hora leilao
                //leilao.setX( noObject.getBoolean("x") );
               	leilao.setTotalTime( noObject.getInt("d") );//tempo total do cronometro leilao
               	leilao.setValueLastLance( noObject.getDouble("p") );//valor do lance atual
               	//leilao.setE( noObject.getBoolean("e") );
               	leilao.setId( noObject.getInt("id") );//id leilao
               	leilao.setDateTimeInitializeLeilao( noObject.getInt("sd") );
               	leilao.setDateTimeLastLance( noObject.getInt("s") );
            	leilao.setTimeOnStopwatch( noObject.getInt("t") );//tempo do cronometro do leilao
            	leilao.setUser( noObject.getString("u").toString() );//nome de usuario
            	
            	//leilaoLogger	=	leilao;
            	
            	if( this.user.isPrinttrafic()==true)
            		printLance( "Print Trafic, ",leilao );            	
            	
            	if( this.user.isSpylance() )
            		spyLance( leilao );
            	
            	
            }
            
    		
            if( this.user.isPrintalllances() || this.user.isPrintmylance() || this.user.isLogger() ){
            	
            	for (Leilao i : this.leilaoLogger){ 
                	
                	if( i.isInsert() ==true ){
                		
                		if( this.user.isPrintalllances() )
                			printLance( "Print all lances, ",i );        
                                              	
                    	if( this.user.isPrintmylance() )
                    		if( i.getUser().equals( this.user.getNickname() ) )
                    			printLance( "Print my lances, ",i );
                        		                                        		
                		if( this.user.isLogger() )
                			saveLance( i );
                		
                		i.setInsert( false );
                	}
            	
                } 
        	
            }
            
            if( this.user.isLogger() ){
            	if( this.user.isRank() )
            		if( this.user.getRowsrank() >0 )
            			showRankTop( this.user.getLeilao(), this.user.getRowsrank() );
            }
            
            if( this.windowInterface.isShowConfigUser() )
    			this.showConfigUser( this.user );
    		
    		
            
    	}catch(Exception e){
    		throw new Exception( "Problemas ao scanear.\nError: "+e.getMessage() );
    	}
		
	}
	
	
	private Leilao findIdLeilaoInList( int id, List<Leilao> leilao1 ){
				
		Leilao	n=null;
		
    	for (Leilao x : leilao1)			
			if( id == x.getId() ){					
				n=x;	
				break;
			}      
            	
    	return n;
	}
	
//	private void update( Leilao leilao ) throws Exception{
//		
//		Leilao findx = this.findIdLeilaoInList( leilao.getId(), this.leilaoLogger );
//		
//    	if( findx == null ){
//    		leilao.setInsert( true );
//			this.leilaoLogger.add( leilao );			
//		}else{
//			
//			if( findx.getUser().equals( leilao.getUser() ) ){
//				if( leilao.getValueLastLance() == findx.getValueLastLance() ){
//					findx.setTimeOnStopwatch( leilao.getTimeOnStopwatch() );
//				}else{
//					leilao.setTimeOnStopwatch( findx.getTimeOnStopwatch() );					
//					this.leilaoLogger.remove( findx );
//					
//					leilao.setInsert( true );
//					this.leilaoLogger.add( leilao );
//				}
//			}else{
//				leilao.setTimeOnStopwatch( findx.getTimeOnStopwatch() );	
//				this.leilaoLogger.remove( findx );
//				
//				leilao.setInsert( true );
//				this.leilaoLogger.add( leilao );
//			}
//		}		
//	}

//	private void insert( Leilao leilao ) throws Exception{
//		
//		try{
//			this.leilaoLogger.add( leilao );
//			saveLance( leilao );
//		}catch( Exception e){
//			throw new Exception( e.getMessage() );
//		}
//		
//	}
	
	private void spyLance( Leilao leilao ) throws Exception{
		

		try{ 
			
			Leilao findx = this.findIdLeilaoInList( leilao.getId(), this.leilaoLogger );
			
	    	if( findx == null ){
	    		leilao.setInsert( true );
				this.leilaoLogger.add( leilao );			
			}else{
				
				if( findx.getUser().equals( leilao.getUser() ) ){
					if( leilao.getValueLastLance() == findx.getValueLastLance() ){
						findx.setTimeOnStopwatch( leilao.getTimeOnStopwatch() );
					}else{
						leilao.setTimeOnStopwatch( findx.getTimeOnStopwatch() );					
						this.leilaoLogger.remove( findx );
						
						leilao.setInsert( true );
						this.leilaoLogger.add( leilao );
					}
				}else{
					leilao.setTimeOnStopwatch( findx.getTimeOnStopwatch() );	
					this.leilaoLogger.remove( findx );
					
					leilao.setInsert( true );
					this.leilaoLogger.add( leilao );
				}
			}
	    	
    	}catch(Exception e){      		
    		throw new Exception( "Error in registry logger: "+e.getMessage() );
    		
    	}
		
	}


	
	public void scannerId( int id ) throws Exception{
		
		try{
        	
        	//final String json = "[{\"lb\":\"leojaera|fabiotadeu|caiolw|fabiotadeu|victorfialho23|fabiotadeu|tcbatista|silas86|drimdri|fabiotadeu|\",\"w\":0,\"st\":\"21 de Nov de 2011, 15:30\",\"x\":false,\"d\":20,\"p\":5.91,\"e\":false,\"id\":6042,\"sd\":1321894800,\"pc\":\"99.0\",\"s\":1321896649,\"bv\":0.01,\"t\":\"19\",\"u\":\"leojaera\"}, {\"st\":\"21 de Nov de 2011, 15:30\",\"x\":false,\"d\":15,\"p\":0.69,\"e\":false,\"id\":6043,\"sd\":1321898400,\"s\":1321896649,\"t\":\"15\",\"u\":\"peixotobh\"}, {\"st\":\"21 de Nov de 2011, 15:30\",\"x\":false,\"d\":20,\"p\":0.11,\"e\":false,\"id\":6046,\"sd\":1321900200,\"s\":1321896649,\"t\":\"20\",\"u\":\"carolinem\"}, {\"st\":\"21 de Nov de 2011, 15:30\",\"x\":false,\"d\":30,\"p\":0.19,\"e\":false,\"id\":6048,\"sd\":1321903800,\"s\":1321896649,\"t\":\"30\",\"u\":\"aposta57\"}]";	
    		//final String json = "f1('[{\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":20,\"p\":18.86,\"e\":false,\"id\":6042,\"sd\":1321894800,\"s\":1321902329,\"t\":\"17\",\"u\":\"peixao\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":15,\"p\":11.73,\"e\":false,\"id\":6043,\"sd\":1321898400,\"s\":1321902329,\"t\":\"15\",\"u\":\"peixotobh\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":20,\"p\":5.18,\"e\":false,\"id\":6046,\"sd\":1321900200,\"s\":1321902329,\"t\":\"19\",\"u\":\"ha_muquirana\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":30,\"p\":0.22,\"e\":false,\"id\":6048,\"sd\":1321903800,\"s\":1321902329,\"t\":\"30\",\"u\":\"anderson1234\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":30,\"p\":0.31,\"e\":false,\"id\":6049,\"sd\":1321912800,\"s\":1321902329,\"t\":\"30\",\"u\":\"camilalapa\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":15,\"p\":1.36,\"e\":false,\"id\":6047,\"sd\":1321916400,\"s\":1321902329,\"t\":\"15\",\"u\":\"melissapinheiro\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":20,\"p\":0.16,\"e\":false,\"id\":6050,\"sd\":1321923600,\"s\":1321902329,\"t\":\"20\",\"u\":\"anderson1234\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":20,\"p\":0.31,\"e\":false,\"id\":6051,\"sd\":1321927200,\"s\":1321902329,\"t\":\"20\",\"u\":\"julinhoramos08\"}, {\"st\":\"21 de Nov de 2011, 17:05\",\"x\":false,\"d\":30,\"p\":0.15,\"e\":false,\"id\":6052,\"sd\":1321963200,\"s\":1321902329,\"t\":\"30\",\"u\":\"mariomrdesign\"}]');";
         	
    		Double microtime 	= 	(double) (System.currentTimeMillis() );      	
        	DecimalFormat df 	=	new DecimalFormat("##,###########");        	  
        	String currenttime	=	df.format(microtime);
        	
    		String url 			= 	"http://request3.mukirana.com/" +
    								"jsons/auctions_for_show_auction_"
    								+id+"?_="+currenttime;//9.175279440106525";
    		
    		String json 		= 	this.http.get( url );
    		
    		//url para saber o que significa cada id de leilao
    		//http://request2.mukirana.com/jsons/load_auctions_for_show_6043?_=19.369437160053558    			
    		//System.out.println( "\n\n" );
    		
        	String strClear = json.substring(4, json.length()-3);
         	JSONArray jObject = new JSONArray(strClear);

            for (int i = 0; i < jObject.length(); i++) {
            	
            	JSONObject noObject = jObject.getJSONObject(i);            	
            	
            	if( noObject.getInt("id") == id ){
            		
	            	Leilao leilao = new Leilao();            	
	               	
	               	leilao.setDateTimeLastLanceFormat( noObject.getString("st").toString() );//data hora leilao
	                //leilao.setX( noObject.getBoolean("x") );
	               	leilao.setTotalTime( noObject.getInt("d") );//tempo total do cronometro leilao
	               	leilao.setValueLastLance( noObject.getDouble("p") );//valor do lance atual
	               	//leilao.setE( noObject.getBoolean("e") );
	               	leilao.setId( noObject.getInt("id") );//id leilao
	               	leilao.setDateTimeInitializeLeilao( noObject.getInt("sd") );
	               	leilao.setDateTimeLastLance( noObject.getInt("s") );
	            	leilao.setTimeOnStopwatch( noObject.getInt("t") );//tempo do cronometro do leilao
	            	leilao.setUser( noObject.getString("u").toString() );//nome de usuario
	            	
	            	scannerLance( leilao );
	            	
	            	if( this.user.isPrinttrafic()==true)
	            		printLance( "Print Trafic, ",leilao );
	            	
	            	if( this.user.isSpylance() )
	            		spyLance( leilao );
            		
            		break;
            		
            	}
	            	
            	
            }
            

            if( this.user.isPrintalllances() || this.user.isPrintmylance() || this.user.isLogger() ){
            	
            	for (Leilao i : this.leilaoLogger){ 
                	
                	if( i.isInsert() ==true ){
                		
                		if( this.user.isPrintalllances() )
                			printLance( "Print all lances, ",i );        
                                              	
                    	if( this.user.isPrintmylance() )
                    		if( i.getUser().equals( this.user.getNickname() ) )
                    			printLance( "Print my lances, ",i );
                        		                                        		
                		if( this.user.isLogger() )
                			saveLance( i );
                		
                		i.setInsert( false );
                	}
            	
                } 
        	
            }
            
            if( this.user.isRank() ){
            	if( this.user.isLogger() )
            		if( this.user.getRowsrank() >0 )
            			showRankTop( this.user.getLeilao(), this.user.getRowsrank() );
            }
            
            if( this.windowInterface.isShowConfigUser() )
    			this.showConfigUser( this.user );
    		
    		
            
    	}catch(Exception e){
    		throw new Exception( "\n\nProblemas ao scanear leilao:"
    								+id+"\nError: "+e.getMessage() );
    	}
		
	}


	private void scannerLance( Leilao leilao ) throws Exception{
		

		try{ 

	    	if(leilao.getTimeOnStopwatch() < leilao.getTotalTime() )
	    	{	    		
	    		if( leilao.getTimeOnStopwatch()  <= this.user.getLimit() ){	    			
	    			
	    			if( this.authentication ){//verify user login
		    			
	    				if( this.user.getCredit() > 0 ){
	    				
	    					if( !leilao.getUser().equals( user.getNickname() ) ){		    				
			    				
		    					if( this.user.getMaxlance()==0 ){
		    						
				    				lance( leilao.getId() );//dar o lance
				    				
				    				this.qtdLances++;
				    				
				    				if( this.user.isBeep() )
				    					this.toolkit.beep();
				    						    						
		    					}else{	    					    					
				    				
		    						if( this.qtdLances < this.user.getMaxlance() ){			    					
				    									    		
					    				lance( leilao.getId() );//dar o lance
					    				
					    				this.qtdLances++;
					    				
					    				if( this.user.isBeep() )
					    					this.toolkit.beep();
					    				
				    				}else{
				    					this.messageBox( "Encerrou o numero maximo de lances definido pelo usuario", true );	
				    				}
			    				}		    			
			    			}
	    					
	    				}else{
	    					this.messageBox( "Voce nao possui credito suficiente", true );	    					
	    					
	    				}
	    					
	    			}
	    		}
	    				    		
	    	}	    	
    	
    	}catch(Exception e){      		
    		throw new Exception( "Error scan leilao id="
    							+leilao.getId()+".\nError:"+e.getMessage() );
    		
    	}
		
	}
	
	
	private void lance( int id ) throws Exception{
    	
    	String targetURL="";
    	String urlParameters="";
    	String html="";
    	
    	targetURL	 =	"http://www.mukirana.com/bids/create/"+id;
        urlParameters =	"auction_id="+id+"&commit=Lance";
        
        try{
        	
       
        html = this.http.post( targetURL, urlParameters );
        
        String saldo = "";
		String tag = "message_auction_"+id+"\", \"";
		
		saldo = html.substring( html.indexOf(tag)+tag.length(), html.length() );
		saldo = saldo.substring(0, saldo.indexOf("\""));
		
		if( saldo.equals( "comprar lances" ) )
			saldo = "0";
		
		this.user.setCredit( Integer.parseInt( saldo ) );
		
        }catch( Exception e ){
        	throw new Exception( "Error lance, id="+
									+id+". Error:"+e.getMessage() );	 
        }
        //System.out.println( "\nlance dado, id="+id );
        //System.out.println( ""+html+"\n" );        
    }
	
	
//	private boolean verifyLance( Leilao leilao )throws Exception{
//		
//		boolean exists	=	false;
//    	
//    	try{
//    	
//
//	        if( this.connection != null ){        	
//	        
//		        Statement stm	=	this.connection.createStatement();    
//		        
//		        String query	=	"Select count(*) qtd from usuario where "			
//		        							+"	usuario='"+leilao.getUser()
//		        							+"' and idleilao="+leilao.getId()
//		        							//+" and data='"+data+"'"
//		        							+" and lance="+leilao.getValueLastLance();
//		        							  		
//
//		        // Definido o Statement, executamos a query no banco de dados  
//		        ResultSet rs = stm.executeQuery( query );  
//		        
//		        String qtd ="";
//		         
//		        while(rs.next()) 
//		        	qtd = rs.getString("qtd"); 
//		        		        
//		        int valor = Integer.parseInt( qtd );
//		        
//		        if( valor>0 )
//		        	exists=true;
//		        else
//		        	exists=false;
//			        
//	        }
//    
//    	}catch( Exception e){
//    		throw new Exception( "Error consult user\nError:"+e.getMessage() );
//    	
//    	}
//        
//	    return exists;
//	}
	
	
	private void showRankTop( int id, int rows ) throws Exception{
		    	
    	try{
    	

	        if( this.connection != null ){        	
	        
		        Statement stm	=	this.connection.createStatement();    
		        
		        String query	=	"Select count(*) qtd from usuario where "			
						+"	idleilao="+id;
		        
		        ResultSet rs = stm.executeQuery( query );  
		       
		        int qtd=0;
		        while(rs.next())
		        	qtd=rs.getInt("qtd");
		        			
		        
		        if( qtd>0 ){
		        
			        query	=	"Select usuario, count(usuario) arremates from usuario where "			
			        							+"	idleilao="+id
			        							+" group by usuario "
			        							+ "order by arremates desc "
			        							+" limit 0,"+rows;
			        							  		
			        // Definido o Statement, executamos a query no banco de dados  
			        rs = stm.executeQuery( query );  
			        
			        printText("|------------------------------------------------------\n");
			        printText("\tRank users lances - top "+
			        			this.user.getRowsrank()+
			        			" - id leilao "+
			        			this.user.getLeilao()+"\n>| "+
			        			this.formatprint(30,"user")+"| "+
			        			this.formatprint(10,"lances")+
			        			"|\n");
			        int i=0;
			        while(rs.next()){
			        	i++;			        	
			        	printText( this.formatprint(30,"|"+i+"| "+rs.getString("usuario"))+"  "
			        				+"| "+this.formatprint(10,""+rs.getInt("arremates") )
			        				+"|\n");
			    
			        }
			        
			        printText("|------------------------------------------------------\n");

			        
		        }else{
		        	
		        	this.messageBox("Nenhum usuario encontrado, tente novamente", true );
		        }
		        
		        
		        rs.close();
		        
		        
	        }
    
    	}catch( Exception e){
    		throw new Exception( "Error consult rank top. Error:"+e.getMessage() );
    	
    	}
        		
	}
	
	
	private void saveLance( Leilao leilao )throws Exception{
		
		try{
    		
	    	if( this.user.getStoregetype().equals( "mysql" ) ){
	    		
	    		if( this.connection != null ){        	
		        	   
		        	//boolean exists	=	verifyLance( leilao );

		        	//if( exists==false ){
			        	
				        // Vamos executar o seguinte comando SQL :  
				        String query = "INSERT INTO usuario (usuario,lance," +
				        				"idleilao,data,contador,datahoralocal," +
				        				"datainicioleilao,dataultimolance) " +
				        				"values ('"+leilao.getUser()+"',"
				        				+leilao.getValueLastLance()
				        				+","+leilao.getId()
				        				+",'"+leilao.getDateTimeLastLanceFormat()
				        				+"',"+leilao.getTimeOnStopwatch()
				        				+",now()"
				        				+","+leilao.getDateTimeInitializeLeilao()
				        				+","+leilao.getDateTimeLastLance()+")";  
							        
				        Statement stm = this.connection.createStatement();  
				        //System.out.println( query );
				        stm.executeUpdate( query );
			        
			      // }		           
		        
		        }else{
		        	
		        	throw new Exception( "Error database not connect" );
		        }
	    		
	    	}else if( this.user.getStoregetype().equals( "file" ) ){
	    		
	    		//implements
	    		
	    	}else{
	    		
//	    		printText("selecione o tipo de armazenamento");
	    		
	    	}
	        
	        
    	}catch( Exception e ){
    		throw new Exception( "Error save user: "+e.getMessage() );
    		
    	}
		
	}
	
	
	public String formatprint( int width, String st) {

		
		if( st.length()> width ){
			st = st.substring(0, width );
		}else{
			
			int x = width-st.length();
			
			for(int i=0; i< x; i++){
				st = st+" ";
			}
		}
		
	    return st;
	 }
	  
	  
	private void messageBox( String text, boolean pause ){
		
		this.windowInterface.messageBox( text );
		this.windowInterface.setTitle( this.windowInterface.getTitle()+"Pause("+pause+")" );
		this.windowInterface.setPauseApplication( pause );
	}
	
	
	private void printText( String text ){
//		System.out.print( text+"\n" );
		windowInterface.printText( ">"
									+ text );
	}
	
	private void printLance( String source, Leilao leilao ){
		
		//print all variables console
//		System.out.print( source
//							+"id:"+leilao.getId()
//							+", user:"+leilao.getUser()
//							+", lance:"+leilao.getValueLastLance()
//							+", cronometro:"+leilao.getTimeOnStopwatch()
//							+", data hora:"+leilao.getDateTimeLastLanceFormat()
//							+"\n" );
		
		Locale locale = new Locale("pt","BR");
    	GregorianCalendar calendar = new GregorianCalendar();
    	SimpleDateFormat formatador = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss",locale);    	
    	String datahora = formatador.format(calendar.getTime());
    	
		windowInterface.printText( ">"
							+ source
							+""+leilao.getId()
							+", "+leilao.getUser()
							+", "+leilao.getValueLastLance()
							+", "+leilao.getTimeOnStopwatch()
							+", "+leilao.getDateTimeLastLanceFormat()
							+", "+datahora
							+"\n" );
		
	}
	
	
	public void showConfigUser( User user ){
		
		//print all variables console
//		System.out.print( source
//							+"id:"+leilao.getId()
//							+", user:"+leilao.getUser()
//							+", lance:"+leilao.getValueLastLance()
//							+", cronometro:"+leilao.getTimeOnStopwatch()
//							+", data hora:"+leilao.getDateTimeLastLanceFormat()
//							+"\n" );
		
		Locale locale = new Locale("pt","BR");
    	GregorianCalendar calendar = new GregorianCalendar();
    	SimpleDateFormat formatador = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss",locale);    	
    	String datahora = formatador.format(calendar.getTime());
    	
		windowInterface.printText( ">Iniciado em "+datahora+"\n"
							+ "username:"+user.getUsername()+"\n"
							+ "password:***\n"
							+ "limit:"+user.getLimit()+"\n"
							+ "maxlance:"+user.getMaxlance()+"\n"
							+ "leilao:"+user.getLeilao()+"\n"
							+ "authentic:"+user.isAuthentic()+"\n"
							+ "mode:"+user.getMode()+"\n"
							+ "maxrepeat:"+user.getMaxrepeat()+"\n"
							+ "delay:"+user.getDelay()+"\n"
							+ "nickname:"+user.getNickname()+"\n"
							+ "printtrafic:"+user.isPrinttrafic()+"\n"
							+ "logger:"+user.isLogger()+"\n"
							+ "beep:"+user.isBeep()+"\n"
							+ "enabled:"+user.isEnabled()+"\n"
							+ "printalllances:"+user.isPrintalllances()+"\n"
							+ "printmylance:"+user.isPrintmylance()+"\n"
							+ "storagetype:"+user.getStoregetype()+"\n"
							+ "spylance:"+user.isSpylance()+"\n"
							+ "databasename:"+user.getDatabasename()+"\n"
							+ "dbuser:"+user.getDbuser()+"\n"
							+ "dbpassword:***\n"
							+ "dbhostip:"+user.getDbhostip()+"\n"
							+ "rank:"+user.isRank()+"\n"
							+ "rowsrank:"+user.getRowsrank()+"\n"
							+"\n" );
		
		this.windowInterface.setShowConfigUser( false );
		
	}
	
}
